package router

import (
	"context"
	"errors"
	"fmt"
	"log"

	"gin-gateway/core/dao"
	"gin-gateway/middleware/tcp_proxy_middleware"
	"gin-gateway/reverse_proxy"
)

var tcpServerList []*reverse_proxy.Server

func TcpProxyServerRun() {
	TcpServiceList := dao.ServiceManagerHandler.GetTcpServiceList()
	for _, serviceItem := range TcpServiceList {
		tempItem := serviceItem
		go func(serviceDetail *dao.ServiceDetail) { // 启动多个tcp Server 端口号
			router := reverse_proxy.NewTcpSliceRouter() // 构造路由，仅用于收集中间件
			router.Group("/").Use(
				tcp_proxy_middleware.TCPFlowCountMiddleware(),
				tcp_proxy_middleware.TCPFlowLimitMiddleware(),
				tcp_proxy_middleware.TCPWhiteAndBlackListMiddleware(), // 黑/白名单 黑名单先校验于 白名单
				// tcp_proxy_middleware.TcpCircuitBreakMiddleware(), // 熔断
				tcp_proxy_middleware.TCPReverseProxyMiddleware(),
			)

			addr := fmt.Sprintf(":%d", serviceDetail.TCPRule.Port)
			tcpServer := &reverse_proxy.Server{
				Addr:    addr,
				Handler: router,
				BaseCtx: context.WithValue(context.Background(), "service", serviceDetail),
			}
			tcpServerList = append(tcpServerList, tcpServer)

			// 启动 tcpServer
			log.Printf("[INFO] TcpProxyServerRun :%v\n", addr)
			if err := tcpServer.ListenAndServe(); err != nil && !errors.Is(err, reverse_proxy.ErrServerClosed) {
				log.Fatalf("[INFO] TcpProxyServerRun %v err:%v\n", addr, err)
			}
		}(tempItem)
	}
}

func TcpProxyServerStop() {
	for _, tcpServer := range tcpServerList {
		tcpServer.Close()
		log.Printf("[INFO] TcpProxyServerStop %v stopped\n", tcpServer.Addr)
	}
}
